<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\Article
 *
 * @property integer $id
 * @property string $title
 * @property integer $article_category_id
 * @property string $content
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property-read \App\Models\ArticleCategory $articleCategory
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article whereTitle($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article whereArticleCategoryId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article whereContent($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article ofTitle($title)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Article ofCategory($article_category_id)
 * @mixin \Eloquent
 */
class Article extends Model
{
    /**
     * 可以被批量賦值的屬性。
     *
     * @var array
     */
    protected $fillable = ['title', 'article_category_id', 'content'];

    /**
     * 获取当前文章的所属分类
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function articleCategory()
    {
        return $this->belongsTo('App\Models\ArticleCategory', 'article_category_id');
    }

    /**
     * 通过文章标题查询
     * @param $query
     * @param $title
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOfTitle($query, $title)
    {
        if (!empty($title)) {
            return $query->where('title', 'like', "%{$title}%");
        } else {
            return $query;
        }
    }

    /**
     * 通过文章分类查询
     * @param $query
     * @param $article_category_id
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOfCategory($query, $article_category_id)
    {
        if (!empty($article_category_id)) {
            if ($article_category_id == 0) {
                return $query;
            } else {
                $sub_ids = ArticleCategory::getAllChildrenIds($article_category_id);
                if(!empty($sub_ids)){
                    return $query->whereIn('article_category_id', $sub_ids);
                }else{
                    return $query->where('article_category_id',$article_category_id);
                }
            }
        } else {
            return $query;
        }
    }

}
